package com.jiuzhe.commercial.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.adapter.CountListAdapter;
import com.jiuzhe.commercial.base.BaseFragment;
import com.jiuzhe.commercial.bean.CountBean;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.http.CallBack;
import com.jiuzhe.commercial.http.HttpClient;
import com.jiuzhe.commercial.utils.SPUtil;
import com.jiuzhe.commercial.utils.UIUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;

/**
 * Created by huanghao on 2018/5/24.
 */

public class CountFragment extends BaseFragment{
    @BindView(R.id.head_title)
    TextView headTitle;
    @BindView(R.id.rv_count)
    RecyclerView rvCount;
    @BindView(R.id.tv_into_time)
    TextView tvIntoTime;
    @BindView(R.id.ib_location)
    ImageView ibLocation;
    @BindView(R.id.ib_add)
    ImageView ibAdd;
    @BindView(R.id.ib_switcher)
    ImageView ibSwitcher;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.tv_average_price)
    TextView tvAveragePrice;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.tv_fee)
    TextView tvFee;
    @BindView(R.id.tv_query)
    TextView tvQuery;
    @BindView(R.id.iv_not)
    ImageView ivNot;
    boolean flag = true;

    private List<CountBean.SkuCountBean> list = new ArrayList<>();
    private CountListAdapter countListAdapter;
    private int year;
    private int month;
    private int day;
    private String mStartDate;
    private String mEndDate;


    @Override
    protected int getLayoutResource() {
        return R.layout.count_fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    private void initView() {
        headTitle.setText("统计");
        ibLocation.setVisibility(View.GONE);
        ibAdd.setVisibility(View.GONE);
        ibSwitcher.setVisibility(View.GONE);
        tvQuery.setVisibility(View.VISIBLE);

        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DAY_OF_MONTH);
        tvIntoTime.setText((month +1) + "月" + day + "日" + "起");
        tvEndTime.setText((month +1) + "月" + day + "日" + "止");

        rvCount.setLayoutManager(new LinearLayoutManager(getContext()));
        rvCount.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL));
        //设置Item增加、移除动画
        //  rvCount.setItemAnimator(new DefaultItemAnimator());
        countListAdapter = new CountListAdapter(list);
        rvCount.setAdapter(countListAdapter);

    }

    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        if (TextUtils.isEmpty(mStartDate) && TextUtils.isEmpty(mEndDate)){
            map.put("beginDate", year + "-" + (month +1) + "-" + day);
            map.put("endDate",  year + "-" + (month +1) + "-" + day);
        }else {
            map.put("beginDate", year + "-" + mStartDate);
            map.put("endDate", year + "-" + mEndDate);
        }
        map.put("merchantId", SPUtil.getString(getContext(),Constants.MERCHANTID));
        map.put("currentPage", "1");
        map.put("number", "5");
        String token = SPUtil.getString(getContext(), Constants.TOKEN);
        String id = SPUtil.getString(getContext(), Constants.ID);
        String autoSignStr = Constants.COUNT.substring(Constants.COUNT.lastIndexOf("0/") + 1) + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        map.put("token", id);
        map.put("sign", signStr);
        HttpClient.post(this, Constants.COUNT, map, new CallBack<CountBean>() {
            @Override
            public void onSuccess(CountBean result) {
                list.clear();
                tvAveragePrice.setText(result.getAvgPrice()+""+"元");
                tvTotal.setText(result.getSumIncome()+"元");
                tvFee.setText(result.getSumBrokerage()+""+"元");
                List<CountBean.SkuCountBean> skuCount = result.skuCount;
                if (skuCount.size()>0){
                    list.addAll(skuCount);
                    countListAdapter.notifyDataSetChanged();
                }else {
                        ivNot.setVisibility(View.VISIBLE);
                        UIUtils.showToastSafe("暂无数据");
                }
            }
        });
    }

    @OnClick({R.id.tv_into_time,R.id.tv_end_time,R.id.tv_query})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_into_time:
                flag = true;
                onMonthDayPicker();
                break;
            case R.id.tv_end_time:
                flag = false;
                onMonthDayPicker();
                break;
            case R.id.tv_query:
                search();
                break;
        }
    }

    /**
     * 查询
     */
    private void search() {
        String  startTime = tvIntoTime.getText().toString().trim();
        String endTime = tvEndTime.getText().toString().trim();
        String str1 = startTime.replace("月","-");
        mStartDate = str1.replace("日","").replace("起","");

        String str2 = endTime.replace("月","-");
        mEndDate = str2.replace("日","").replace("止","");

        String[] stTime = mStartDate.split("-");
        String[] edTime = mEndDate.split("-");

        if (Integer.parseInt(stTime[0]) > Integer.parseInt(edTime[0])){
            UIUtils.showToastSafe("选择查询开始月份大于结束年份");
            return;
        }

        if (Integer.parseInt(stTime[0]) == Integer.parseInt(edTime[0]) && Integer.parseInt(stTime[1]) > Integer.parseInt(edTime[1])){
            UIUtils.showToastSafe("选择查询开始日期大于结束日期");
            return;
        }
        initData();
    }


    private void onMonthDayPicker() {
        DatePicker picker = new DatePicker(getActivity());
        picker.setTextColor(getContext().getResources().getColor(R.color.color_title));
     //   picker.setRange(1960, 2030);
        picker.setSelectedItem(year, month+1, day);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                if (flag){
                    tvIntoTime.setText(month + "月" + day + "日" + "起");
                }else {
                    tvEndTime.setText(month + "月" + day + "日" + "止");
                }
            }
        });
        picker.show();
    }
}
